<template>
  <div class="base-setting-container" v-loading='loading'>
    <h2>{{$t('performance.title.optionSetting')}}</h2>

    <div class="setting-item">
      <p class="setting-title">
        {{$t('performance.title.setApprover')}}

        <el-popover
          placement="top-start"
          trigger="hover"
          :content="$t('performance.placeholder.setApprover')">
          <span style="vertical-align: middle" slot="reference">
            <i class="icon-help iconfont" style="margin-left: 3px;"></i>
          </span>
        </el-popover>

      </p>
      <div class="content">
        <!-- <base-select-user-input
          multiple
          v-model="form.approve"
          :collapse="false"
          placeholder="请设置绩效报告审批人"
        /> -->
        <el-select
          style="width: 300px"
          v-model="form.approve"
          filterable
          clearable
          remote
          multiple
          :placeholder="$t('performance.placeholder.setApprover2')"
          :loading="remoteSearchLoading"
          :remote-method="getApproveList"
          v-el-select-loadmore={loadmoreOptions}
        >
          <el-option
            v-for="item in page.list"
            :key="item.userId"
            :label="item.displayName"
            :origin="item"
            :value="item.userId">
            
            <template v-if="isOpenData">
              <open-data type="userName" :openid="item.staffId"></open-data>
            </template>
            
          </el-option>
          
          <template slot="multiple" slot-scope="{ item }">
            <template v-if="isOpenData && item && item.staffId">
              <open-data type="userName" :openid="item.staffId"></open-data>
            </template>
            <template v-if="!isOpenData">
              {{ item && item.displayName }}
            </template>
          </template>
          
        </el-select>
        
        <el-button type="primary" @click="setApprove" :disabled="settingPending" style="margin: 0 15px;">{{$t('common.base.save')}}</el-button>
      </div>
    </div>


    <div class="setting-item">
      <p class="setting-title">
        {{$t('performance.title.ccOptions')}}

        <el-popover
          placement="top-start"
          trigger="hover"
          :content="$t('performance.placeholder.cc')">
          <span style="vertical-align: middle" slot="reference">
            <i class="icon-help iconfont" style="margin-left: 3px;"></i>
          </span>
        </el-popover>

      </p>
      <div class="setting-cc">
        <span>{{$t('performance.placeholder.selectCcNode')}}</span>
        <el-radio :label="0" @change="changeSetting" v-model="form.sendToCc" :disabled="pending">{{$t('performance.label.ccAfterCreated')}}</el-radio>
        <el-radio :label="3" @change="changeSetting" v-model="form.sendToCc" :disabled="pending">{{$t('performance.label.ccAfterApproved')}}</el-radio>
      </div>
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import {setCcForReport, getApprovePerson, getApprovePersonList, setApprovePerson} from '@src/api/PerformanceApi';
import Page from '@model/Page'

export default {
  name: 'base-setting',
  props: {
    setting: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isOpenData,
      pending: false,
      settingPending: false,
      remoteSearchLoading: false,
      approveList: [],
      form: {
        approve: [],
        sendToCc: false
      },
      loadmoreOptions: {
        disabled: false,
        callback: this.loadmore,
        distance: 10,
      },
      page: new Page(),
      loading: false
    }
  },
  created() {
    this.loading = true
    this.init();
  },
  methods: {
    async loadmore() {
      if (this.loadmoreOptions.disabled) return

      this.loadmoreOptions.disabled = true
      this.page.pageNum += 1

      try {
        const result = await this.fetchRemoteData()
        this.page.merge(result)

      } catch (error) {
        Log.error(error, this.loadmore.name)
      }

    },
    init() {
      this.form.sendToCc = this.setting.sendToCc;
      
      Promise.all([
        this.getApproveInfo(),
        this.getApproveList()
      ])
        .then(res => {
          (res[0] || []).forEach(user => {
            if (this.page.list.every(u => u.userId !== user.userId)) {
              this.page.list = [...this.page.list, user]
            }
          })
        })
        .catch(e => console.error('e', e));
    },
    async getApproveList(keyword) {
      this.page = new Page()
      try {
        const result = await this.fetchRemoteData(keyword)
        this.page.merge(result)
        this.loading = false
      } catch (error) {
        this.loading = false
        Log.error(error, this.loadmore.name)
      }
    },
    async fetchRemoteData(keyword='') {
      const params = { keyword, pageNum: this.page.pageNum, pageSize: 20 }

      try {
        const res = await getApprovePersonList(params)
        const result = res?.data || {}
        this.loadmoreOptions.disabled = Boolean(!result?.hasNextPage)
        return result

      } catch (error) {
        Log.error(error, this.fetchRemoteData.name)
      }
    },
    getApproveInfo() {
      return getApprovePerson()
        .then((res = {}) => {
          res.data ? res.data : res.data = [];
          this.form.approve = res.data.map(({userId}) => userId);
          return res.data;
        })
        .catch(e => console.error('e', e));
    },
    setApprove() {
      this.settingPending = true;
      setApprovePerson({
        reviewIds: this.form.approve.join(','),
      })
        .then(res => {
          this.settingPending = false;
          if (!res) return;
          if (res.status) return this.$platform.notification({
            title: this.$t('common.base.fail'),
            message: res.message || '',
            type: 'error',
          });

          return this.$platform.notification({
            title: this.$t('common.base.success'),
            message: this.$t('performance.title.setApprover'),
            type: 'success',
          });

        })
        .catch(e => console.error('e', e));
    },
    changeSetting() {
      if (this.pending) return;

      this.pending = true;
      setCcForReport({
        flag: this.form.sendToCc,
      })
        .then(res => {
          this.pending = false;

          if (!res) return;
          if (res.status) return this.$platform.notification({
            title: this.$t('common.base.fail'),
            message: res.message || '',
            type: 'error',
          });

          return this.$platform.notification({
            title: this.$t('common.base.success'),
            message: this.$t('performance.title.setCcOptions'),
            type: 'success',
          });
        })
        .catch(e => console.error('e', e));
    }
  },
}
</script>

<style lang="scss">

  .base-setting-container {
    background: #fff;
    margin-bottom: 10px;
    padding: 10px;
    
    .open-data {
      margin-right: 0;
    }

    h2 {
      line-height: 30px;
      border-bottom: 1px solid #ddd;
      font-size: 15px;
      margin-bottom: 10px;
    }

    .setting-item {
      padding-left: 15px;
      line-height: 30px;

      .setting-title {
        font-size: 14px;
        font-weight: 700;
        margin: 0;
      }

      .setting-cc {
        &>span {
          margin-right: 25px;
        }
        label {
          margin-bottom: 0;
        }
      }

      .content {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 10px 0;
      }


    }

  }
</style>

// <style lang="scss">
// .base-setting-container {
//   .base-select-user-input {
//     max-width: 268px;
//   }
// }
// </style>